<?php


namespace app\massage\controller;


use app\adapay\model\Member;
use app\AdminRest;
use app\massage\model\CashUpdateRecord;
use app\massage\model\Coach;
use app\massage\model\Commission;
use app\massage\model\Order;
use app\massage\model\Police;
use app\massage\model\RefundOrder;
use app\massage\model\ShopCarte;
use app\massage\model\ShopGoods;
use app\massage\model\ShortCodeConfig;
use app\massage\model\User;
use app\massage\model\Wallet;
use longbingcore\heepay\HeePay;
use longbingcore\heepay\WeixinPay;
use longbingcore\wxcore\Adapay;
use longbingcore\wxcore\Fdd;
use longbingcore\wxcore\Moor;
use longbingcore\wxcore\WxPay;
use think\cache\driver\Redis;
use think\facade\Cache;
use think\facade\Db;
use LongbingUpgrade;

class AdminShop extends AdminRest
{



    public function changeOpenid(){

        $user_model = new User();

        $list = $user_model->where(['uniacid'=>$this->_uniacid])->field('openid')->order('id desc')->paginate(100)->toArray();

        $token = $this->getGzhToken();

        $url = 'https://api.weixin.qq.com/cgi-bin/changeopenid?access_token='.$token;

        $openidArray = array_column($list['data'],'openid');

       // $openidArray = ['oaGb56SIiypTWFv_VqHWuzLC-TzY'];

        $data['from_appid']="wx8e7b1b00dcef22d3";

        $data['openid_list']= $openidArray;

        $data = json_encode($data);

        $res = lbCurlPost($url,$data);

        $res = json_decode($res,true);

        if(!empty($res['result_list'])){

            foreach ($res['result_list'] as $v){

                if(isset($v['err_msg'])&&$v['err_msg']=='ok'){

                    $user_model->dataUpdate(['openid'=>$v['ori_openid']],['openid'=>$v['new_openid'],'web_openid'=>$v['new_openid']]);
                }

            }
        }

        return $this->success($res);

    }






    /**
     * @author chenniang
     * @DataTime: 2022-02-26 17:19
     * @功能说明:
     */
    public function getGzhToken($update=0){

        $uniacid = $this->_uniacid;

        $appid   = 'wx3d0e6be3e2aee5c4';

        $gzh_secret  = 'a10859055c1c28c4b7bba89b47f63925';

        $key         = 'articleToken-';

        $value = getCache($key, $uniacid);

        if ($value&&$update==0)
        {
            return $value;
        }

        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$gzh_secret}";

        $js_token = file_get_contents($url);

        $js_token = json_decode($js_token, true);

        if (isset($js_token['access_token']))
        {
            $js_token = $js_token['access_token'];

            setCache($key, $js_token, 1200, $uniacid);

            return $js_token;
        }

        $str = '请求ac错误' . isset($js_token['errmsg']) ? $js_token['errmsg'] : '';
        echo $str;
        die;
    }

    /**
     * 添加分类
     * @return \think\Response
     */
    public function addCarte()
    {

        $input = $this->request->only(['name', 'sort']);
        $rule = [
            'name' => 'require',
            'sort' => 'require',
        ];
        $validate = \think\facade\Validate::rule($rule);
        if (!$validate->check($input)) {
            return $this->error($validate->getError());
        }
        $input['name'] = trim($input['name']);
        $where = [
            ['name', '=', $input['name']],
            ['status', 'in', [0, 1]],
            ['uniacid', '=', $this->_uniacid]
        ];
        $info = ShopCarte::getInfo($where);

        if (!empty($info)) {
            return $this->error('此分类已存在，不可创建');
        }
        $input['uniacid'] = $this->_uniacid;
        $res = ShopCarte::add($input);
        if ($res) {
            return $this->success('');
        }

        return $this->error('创建失败');
    }

    /**
     * 编辑分类
     * @return \think\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function editCarte()
    {
        $input = $this->request->only(['id', 'name', 'sort']);
        if ($this->request->isPost()) {
            $rule = [
                'name' => 'require',
                'sort' => 'require',
            ];
            $validate = \think\facade\Validate::rule($rule);
            if (!$validate->check($input)) {
                return $this->error($validate->getError());
            }
            $input['name'] = trim($input['name']);
            $where = [
                ['name', '=', $input['name']],
                ['status', 'in', [0, 1]],
                ['uniacid', '=', $this->_uniacid],
                ['id', '<>', $input['id']]
            ];
            $info = ShopCarte::getInfo($where);
            if (!empty($info)) {
                return $this->error('此分类已存在，不可编辑');
            }
            $res = ShopCarte::update($input, ['id' => $input['id']]);
            if ($res === false) {
                return $this->error('编辑失败');
            }
            return $this->success('');
        }
        if (empty($input['id'])) {
            return $this->error('参数错误');
        }
        $info = $info = ShopCarte::getInfo(['id' => $input['id']]);
        return $this->success($info);
    }

    /**
     * @author chenniang
     * @DataTime: 2023-10-26 17:06
     * @功能说明:获取技师上个半月可提现的金额
     */
    public function getCoachCashByHalfMonthV2($coach_id,$true_cash,$type=1){

        $half = strtotime(date('Y-m-16'));

        if(time()>=$half){

            $time = strtotime(date('Y-m-01'));

        }else{

            $time = strtotime(date('Y-m-16',strtotime('-1 month')));
        }

        //前15天的
        // $time = 15*86400;

        // $time = 86400;

        $order_model = new Order();

        $dis[] = ['a.pay_type','=',7];

        $dis[] = ['b.status','=',2];

        $dis[] = ['b.top_id','=',$coach_id];

        $dis[] = ['a.create_time','<=',$time];
        //服务费
        if($type==1){

            $dis[] = ['b.type','in',[3,7]];
        }else{
            //车费
            $dis[] = ['b.type','in',[8]];
        }

        $cash  = $order_model->alias('a')
            ->join('massage_service_order_commission b','a.id = b.order_id')
            ->where($dis)
            ->group('b.id')
            ->sum('b.cash');

        $wallet_model = new Wallet();

        $where[] = ['coach_id','=',$coach_id];

        $where[] = ['status','in',[1,2,4,5]];

        if($type==1){

            $where[] = ['type','=',1];

        }else{
            $where[] = ['type','=',2];
        }

        $wallt_cash = $wallet_model->where($where)->sum('total_price');

        $update_model = new CashUpdateRecord();

        if($type==1){

            $add_update_cash = $update_model->where(['coach_id'=>$coach_id,'status'=>1,'is_add'=>1])->where('create_time','<=',$time)->sum('cash');

            $del_update_cash = $update_model->where(['coach_id'=>$coach_id,'status'=>1,'is_add'=>0])->where('create_time','<=',$time)->sum('cash');

            $coach_cash = $cash-$wallt_cash+$add_update_cash-$del_update_cash;
        }else{

            $coach_cash = $cash-$wallt_cash;
        }

        $order_model = new Order();

        $aa = Db::name('massage_service_order_commission')->where(['top_id'=>21,'type'=>3,'status'=>2])->column('order_id');


        $order_id = $order_model->where(['coach_id'=>21,'pay_type'=>7])->where('id','not in',$aa)->column('id');




        $coach_cash = $coach_cash>0?$coach_cash:0;

        $coach_cash = $coach_cash>$true_cash?$true_cash:$coach_cash;

        return round($coach_cash,2);
    }




    public function coachCashInit($coach_id){

        $comm_model = new Commission();

        $order_id = Db::name('massage_service_order_commission')->where(['top_id'=>21,'type'=>3])->where('status','>',-1)->column('order_id');







    }


    /**
     * @author chenniang
     * @DataTime: 2023-10-26 17:06
     * @功能说明:获取技师上个半月可提现的金额
     */
    public function getCoachCashByHalfMonth($coach_id,$true_cash,$type=1){
        //前15天的
        $time = 15*86400;

        $order_model = new Order();

        $dis[] = ['a.pay_type','=',7];

        $dis[] = ['b.status','=',2];

        $dis[] = ['b.top_id','=',$coach_id];

        $dis[] = ['a.create_time','<=',time()-$time];
        //服务费
        if($type==1){

            $dis[] = ['b.type','in',[3,7]];
        }else{
            //车费
            $dis[] = ['b.type','in',[8]];
        }

        $cash  = $order_model->alias('a')
            ->join('massage_service_order_commission b','a.id = b.order_id')
            ->where($dis)
            ->group('b.id')
            ->sum('b.cash');

        $wallet_model = new Wallet();

        $where[] = ['coach_id','=',$coach_id];

        $where[] = ['status','in',[1,2,4,5]];

        // $where[] = ['create_time','<=',time()-$time];

        if($type==1){

            $where[] = ['type','=',1];

        }else{
            $where[] = ['type','=',2];
        }

        $wallt_cash = $wallet_model->where($where)->sum('total_price');

        $update_model = new CashUpdateRecord();

        if($type==1){

            $add_update_cash = $update_model->where(['coach_id'=>$coach_id,'status'=>1,'is_add'=>1])->where('create_time','<=',time()-$time)->sum('cash');

            $del_update_cash = $update_model->where(['coach_id'=>$coach_id,'status'=>1,'is_add'=>0])->where('create_time','<=',time()-$time)->sum('cash');

            $coach_cash = $cash-$wallt_cash+$add_update_cash-$del_update_cash;
        }else{

            $coach_cash = $cash-$wallt_cash;
        }

        $coach_cash = $coach_cash>0?$coach_cash:0;

        $coach_cash = $coach_cash>$true_cash?$true_cash:$coach_cash;

        return round($coach_cash,2);
    }

    /**
     * 分类列表
     * @return \think\Response
     * @throws \think\db\exception\DbException
     */
    public function carteList(){


//        $a = $this->getCoachCashByHalfMonth(20,147.66,2);
//
//        dump($a);exit;

      //  $coach_model = new



        $input = $this->_param;

        $limit = $this->request->param('limit', 10);

        $where = [

            ['uniacid', '=', $this->_uniacid],

            ['status', '<>', '-1']
        ];

        if(!empty($input['name'])){

            $where[] = ['name','like','%'.$input['name'].'%'];

        }

        $data = ShopCarte::getList($where, $limit);

        return $this->success($data);
    }

    /**
     * 上下架、删除
     * @return \think\Response
     */
    public function carteStatus()
    {
        $input = $this->request->only(['id', 'status']);
        $rule = [
            'id' => 'require',
            'status' => 'require|in:0,1,-1',
        ];
        $validate = \think\facade\Validate::rule($rule);
        if (!$validate->check($input)) {
            return $this->error($validate->getError());
        }
        if ($input['status'] == -1) {
            $where = [
                ['', 'exp', Db::raw("find_in_set({$input['id']},carte)")],
                ['status', '<>', '-1'],
                ['uniacid', '=', $this->_uniacid]
            ];
            $info = ShopGoods::getInfo($where);
            if (!empty($info)) {
                return $this->error('此分类下有商品，不可删除');
            }
        }
        $res = ShopCarte::update(['status' => $input['status']], ['id' => $input['id']]);
        if ($res === false) {
            return $this->error('操作失败');
        }
        return $this->success('');
    }

    /**
     * 下拉
     * @return \think\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function goodsCarteList()
    {
        $list = ShopCarte::getListNoPage(['status' => 1, 'uniacid' => $this->_uniacid]);
        return $this->success($list);
    }

    /**
     *添加商品
     * @return \think\Response
     */
    public function addGoods()
    {
        $input = $this->request->only(['name', 'carte', 'cover', 'images', 'image_url', 'video_url', 'phone', 'desc', 'sort', 'price']);
        $rule = [
            'name' => 'require',
            'carte' => 'require',
            'cover' => 'require',
            'images' => 'require',
            'phone' => 'require',
            'desc' => 'require',
            'price' => 'require',
        ];
        $validate = \think\facade\Validate::rule($rule);
        if (!$validate->check($input)) {
            return $this->error($validate->getError());
        }
        $input['create_time'] = time();
        $input['images'] = json_encode($input['images']);
        $input['carte'] = implode(',', $input['carte']);
        $input['uniacid'] = $this->_uniacid;
        $res = ShopGoods::insert($input);
        if ($res) {
            return $this->success('');
        }
        return $this->error('添加失败');
    }

    /**
     * 编辑商品
     * @return \think\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function editGoods()
    {
        $input = $this->request->only(['id', 'name', 'carte', 'cover', 'images', 'image_url', 'video_url', 'phone', 'desc', 'sort', 'price']);
        if ($this->request->isPost()) {
            $rule = [
                'id' => 'require',
                'name' => 'require',
                'carte' => 'require',
                'cover' => 'require',
                'images' => 'require',
                'phone' => 'require',
                'desc' => 'require',
                'price' => 'require',
            ];
            $validate = \think\facade\Validate::rule($rule);
            if (!$validate->check($input)) {
                return $this->error($validate->getError());
            }
            $input['images'] = json_encode($input['images']);
            $input['carte'] = implode(',', $input['carte']);
            $input['uniacid'] = $this->_uniacid;
            $res = ShopGoods::update($input, ['id' => $input['id']]);
            if ($res === false) {
                return $this->error('编辑失败');
            }
            return $this->success('');
        }
        if (empty($input['id'])) {
            return $this->error('参数错误');
        }
        $data = ShopGoods::getInfo(['id' => $input['id']]);
        $data['carte'] = explode(',', $data['carte']);
        $data['images'] = json_decode($data['images'], true);
        return $this->success($data);
    }

    /**
     * 商品列表
     * @return \think\Response
     * @throws \think\db\exception\DbException
     */
    public function goodsList()
    {
        $input = $this->request->param();
        $limit = $this->request->param('limit', 10);
        $where = [];
        $where[] = ['status', '<>', -1];
        $where[] = ['uniacid', '=', $this->_uniacid];
        if (!empty($input['name'])) {
            $where[] = ['name', 'like', '%' . $input['name'] . '%'];
        }
        if (!empty($input['carte'])) {
            $where[] = ['', 'exp', Db::raw("find_in_set({$input['carte']},carte)")];
        }
        $data = ShopGoods::getList($where, $limit);
        return $this->success($data);
    }

    /**
     * 上下架删除
     * @return \think\Response
     */
    public function goodsStatus()
    {
        $input = $this->request->only(['id', 'status']);
        $rule = [
            'id' => 'require',
            'status' => 'require|in:0,1,-1',
        ];
        $validate = \think\facade\Validate::rule($rule);
        if (!$validate->check($input)) {
            return $this->error($validate->getError());
        }
        $res = ShopGoods::update(['status' => $input['status']], ['id' => $input['id']]);
        if ($res === false) {
            return $this->error('操作失败');
        }
        return $this->success('');
    }
}